<?php
/**
 * User: YL
 * Date: 2019/6/10
 */

namespace restful\utils;

use restful\traits\InstanceTrait;
use think\Container as ThinkContainer;

class Env
{
    use InstanceTrait;

    const GET_DELIMITER = '_';
    const SET_DELIMITER = '.';

    private function __construct()
    {
        $file = ThinkContainer::getInstance()->get('app')->getRootPath() . '.env';
        $this->load($file);
    }

    /**
     * 获取环境变量
     * @param string $name
     * @param null $default
     * @return mixed
     */
    public static function get(string $name = null, $default = null)
    {
        // 初始化自己
        static::getInstance();

        if (empty($name)) {
            return $_ENV;
        }

        $name = strtolower(str_replace(static::SET_DELIMITER, static::GET_DELIMITER, $name));

        if (isset($_ENV[$name])) {
            return $_ENV[$name];
        }

        $data = static::getEnv($name);
        if (! empty($data)) {
            return $data;
        }

        return $default;
    }

    /**
     * 设置环境变量
     * @param $env
     * @param null $value
     */
    public static function set($env, $value = null)
    {
        if (is_array($env)) {
            $env = array_change_key_case($env, CASE_LOWER);

            foreach ($env as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $k => $v) {
                        $_ENV[$key . static::GET_DELIMITER . strtolower($k)] = static::formatValue($v);
                    }
                } else {
                    $_ENV[$key] = static::formatValue($val);
                }
            }
        } else {
            $name = strtolower(str_replace(static::SET_DELIMITER, static::GET_DELIMITER, $env));

            $_ENV[$name] = static::formatValue($value);
        }
    }

    /**
     * 加载并设置环境变量
     * @param string $file
     */
    protected static function load(string $file)
    {
        $env  = parse_ini_file($file, true);
        static::set($env);
    }

    /**
     * 获取环境变量
     * @param string $name
     * @return array
     */
    protected static function getEnv(string $name)
    {
        $name = $name . static::GET_DELIMITER;
        $res  = [];
        foreach ($_ENV as $k => $v) {
            if (stripos($k, $name) === 0) {
                $res[str_replace($name, '', $k)] = $v;
            }
        }
        return $res;
    }

    /**
     * 格式化值
     * @param $str
     * @return mixed
     */
    protected static function formatValue($str)
    {
        if ($str === 'false') {
            return false;
        }
        if ($str === 'true') {
            return true;
        }

        return $str;
    }
}